<template xmlns="">
  <view class="score-page">
    <!-- 房间号展示 -->
    <view class="room-info">
      <text class="room-id">房间号: {{ room.roomId }}</text>
    </view>

    <!-- 积分池 总账模式展示-->
    <view class="score-pool" v-if="room.mode===2">
      <view class="pool-info">
        <text class="pool-title">积分池</text>
        <text class="pool-score">{{ room.scorePool }}</text>
      </view>
      <view class="pool-actions">
        <button class="pool-btn" @click="scoreActionModal.open('01','向积分池给分')">给分</button>
        <button class="take-btn" @click="scoreActionModal.open('02','从积分池取分')">取分</button>
      </view>
    </view>
    <!-- 抽水展示 台费规则：0：无台费，1：满x抽y，2：百分比 -->
    <view class="tax-info" v-if="room.taiwanFee!==0">
      <text v-if="room.taiwanFee==1">台费({{ '满' + room.fullVal + '抽' + room.deductVal }} MAX:{{
          room.taiwanFeeMax
        }}): {{ room.taiwanFeeValue }}
      </text>
      <text v-if="room.taiwanFee==2">台费({{ room.percentValue }}% MAX:{{ room.taiwanFeeMax }}): {{
          room.taiwanFeeValue
        }}
      </text>
    </view>
    <!-- 用户列表 -->
    <view class="user-list">
      <view class="user-card" v-for="user in roomUsers" :key="user.id">
        <view class="avatar-container">
          <image :src="proxy.$tool.getResources(user.avatar)" class="avatar" mode="aspectFill"></image>
        </view>
        <view class="user-info">
          <text class="user-name">{{ user.name }}</text>
          <text class="user-score">
            分数:
            <text :class="user.score>=0?'user-score-number-plus':'user-score-number-minus'" >
              {{ user.score }}
            </text>

          </text>
          <up-transition :show="user.addScoreShow" mode="fade-right" duration="1000">
            <text class="user-score-number-add">+{{user.chnageScoreValue}}</text>
          </up-transition>
          <up-transition :show="user.subScoreShow" mode="fade-right" duration="1000">
            <text class="user-score-number-sub">{{user.chnageScoreValue}}</text>
          </up-transition>
        </view>
        <!--   给分模式和统一记录展示   计分模式,0:统一记，1:给分模式，2：总账模式   -->
        <view class="btns" v-if="room.mode===1 || (room.mode===0 && room.createUser===userInfo.id)">
          <!--    给分模式不能给自己      -->
          <view v-if="room.mode===0 ||  user.userId!==userInfo.id">
            <up-button type="success" size="large" @click="scoreActionModal.open('03',`向${user.name}给分`,user)">给分
            </up-button>
          </view>
          <!--     统一记模式展示     -->
          <view style="margin-left: 20px;">
            <up-button type="warning"
                       size="large"
                       v-if="room.mode===0"
                       @click="scoreActionModal.open('04',`扣除${user.name}积分`,user)">
              扣分
            </up-button>
          </view>
        </view>
      </view>
    </view>

    <!--  结束按钮  -->
    <view class="end-btns">
      <view class="view-record">
        <up-button type="success" size="large" text="查看计分流水"
                   @click="recordPopupRef.open(room.roomId)"></up-button>
      </view>
      <view class="end_game" v-if="room.createUser===userInfo.id">
        <up-button @click="endGameModal.verify()" type="warning" size="large" text="结束比赛"></up-button>
      </view>

    </view>


    <up-modal
        :show="scoreActionModal.show"
        :title="scoreActionModal.title"
        :closeOnClickOverlay="true"
        @confirm="scoreActionModal.confirm()"
        @close="scoreActionModal.close()">
      <view class="slot-content">
        <up-input ref="inputRef"
                  :key="scoreActionModal.show"
                  :focus="scoreActionModal.inputFocus"
                  type="number"
                  @change="scoreActionModal.checkNum"
                  v-model="scoreActionModal.number"></up-input>
      </view>
    </up-modal>

    <up-modal
        :show="endGameModal.show"
        :title="endGameModal.title"
        :showCancelButton="true"
        @confirm="endGameModal.endGame()"
        @cancel="()=>{endGameModal.show=false}">
      <view class="slot-content">
        <rich-text :nodes="endGameModal.content"></rich-text>
      </view>
    </up-modal>

    <recordPopup :isCloseBar="false" ref="recordPopupRef"></recordPopup>


  </view>
</template>

<script setup>
import {ref, computed, getCurrentInstance} from "vue";
import recordPopup from "@/components/recordPopup";
import {useStore} from "vuex";
import {onLoad, onUnload, onPullDownRefresh} from "@dcloudio/uni-app"; // 正确导入 onLoad
import WebSocket from '/common/socket.js';

const {proxy} = getCurrentInstance();
const store = useStore();
const userInfo = computed(() => store.state.userInfo);
//定义房间用户集合
const roomUsers = ref([]);


//定义ws
let ws = null;

//定义房间信息表
const room = ref({
  //房间id
  roomId: null,
  //计分模式,0:统一记，1:给分模式，2：总账模式
  mode: null,
  //台费规则：0：无台费，1：满x抽y，2：百分比
  taiwanFee: null,
  //得分满多少抽水
  fullVal: null,
  //抽分比例
  deductVal: null,
  //抽水分数
  pumpWaterValue: 0,
  //积分池
  scorePool: 0,
});
onPullDownRefresh(() => {
  initFun(room.value.roomId, () => {
    uni.stopPullDownRefresh(); // 停止刷新动画
  });
})


//定义页面加载事件
onLoad((options) => {
  const id = options.id; // 获取参数 id
  //设置当前房间id
  room.value.roomId = id;
  initFun(id);
});


/**
 * 初始化方法
 * @param fun：回调方法
 */
const initFun = (id, fun) => {
  if (id) {
    //存在id查询
    proxy.$request.get(`/bus-room/get-by-id/${id}`).then(res => {
      room.value = res;
      roomUsers.value = res.roomUsers;
      roomUsers.value.forEach(x => {
        //给每个用户设置自己的动画
        x.addScoreShow = false;
        x.subScoreShow = false;
        x.chnageScoreValue = 0;
      })
      //连接socket
      initSocket(id);
      if (fun) {
        fun();
      }
    })
  } else {
    uni.$u.toast(`房间加载异常！`)
  }
}

/**
 * 离开页面前的回调
 */
onUnload(() => {
  //离开页面关闭socket连接
  ws.close();
})


//初始化socket
const initSocket = (roomId) => {
  // ws = new WebSocket(`/${roomId}/${userInfo.value.id}`);
  ws = WebSocket.getInstance(`/${roomId}/${userInfo.value.id}`)
  // 注册消息处理函数
  ws.onMessage((msg) => {
    //判断消息类型
    switch (msg.type) {
      case "5": //分数变化消息
        //更新消息池积分
        room.value.scorePool = msg.data.busRoom.scorePool;
        //更新台费
        room.value.taiwanFeeValue = msg.data.busRoom.taiwanFeeValue;
        //更新用户积分
        msg.data.roomUsers.forEach(x => {
          //找出当前用户
          let index = roomUsers.value.findIndex(item => item.userId === x.userId);
          //计算分数是否发生变化
          roomUsers.value[index].chnageScoreValue = x.score - roomUsers.value[index].score;
          if (roomUsers.value[index].chnageScoreValue > 0) {
            //分数增加
            roomUsers.value[index].addScoreShow = true;
            setTimeout(() => {
              roomUsers.value[index].addScoreShow = false;
            }, 1500)
          }
          if (roomUsers.value[index].chnageScoreValue < 0) {
            //分数减少
            roomUsers.value[index].subScoreShow = true;
            setTimeout(() => {
              roomUsers.value[index].subScoreShow = false;
            }, 1500)
          }
          roomUsers.value[index].score = x.score;
        })

        break;
      case "6": //结束游戏
        uni.$u.toast(`游戏已经结束,即将退出房间！`)
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/index'
          });
        }, 1000)
        break;
    }
  });
}


//分数操作弹框控制
const scoreActionModal = ref({
  //控制显示
  show: false,
  //分数
  number: null,
  //动作类型
  action: "01",
  //标题
  title: "",
  //输入框聚焦
  inputFocus: false,
  //防止重复提交
  loading: false,
  //当前选中用户
  user: null,


  //启动加载
  loadingOpen: () => {
    scoreActionModal.value.loading = true;
  },
  //关闭加载
  loadingOff: () => {
    setTimeout(() => {
      scoreActionModal.value.loading = false;
    }, 1000)
  },

  //输入检测
  checkNum: e => {
    let value = e;
    // 保留数字和小数点，限制小数点后最多两位
    value = value.replace(/[^0-9.]/g, ""); // 只允许输入数字和小数点
    value = value.replace(/\.{2,}/g, "."); // 防止输入多个小数点
    value = value.replace(/^0+(\d)/, "$1"); // 防止数字以 0 开头
    value = value.replace(/^(\d+)\.(\d{3,})$/, "$1.$2"); // 限制小数点后最多两位

    // 如果有小数点，限制小数点后两位
    const parts = value.split(".");
    if (parts.length > 1 && parts[1].length > 2) {
      value = `${parts[0]}.${parts[1].substring(0, 2)}`;
    }
    //输入的金额被格式化了
    if (value !== e) {
      setTimeout(() => {
        scoreActionModal.value.number = value;
      }, 0)
    }
  },

  //打开方法
  open: (action, title, user) => {
    scoreActionModal.value.number = null;
    scoreActionModal.value.action = action;
    scoreActionModal.value.title = title;
    scoreActionModal.value.user = user;
    scoreActionModal.value.show = true;
    setTimeout(() => {
      scoreActionModal.value.inputFocus = true
    }, 100)
  },

  //关闭方法
  close: () => {
    scoreActionModal.value.inputFocus = false
    setTimeout(() => {
      scoreActionModal.value.show = false;
    }, 100)
  },

  //确认方法
  confirm: () => {
    //判断是否输入内容
    if (!scoreActionModal.value.number) {
      return;
    }
    //防止重复提交
    if (scoreActionModal.value.loading) {
      return;
    }
    scoreActionModal.value.loadingOpen();
    //判断打开类型
    switch (scoreActionModal.value.action) {
      case "01":    //向积分池给分
        scorePool.value.givePool();
        break
      case "02":    //从积分池取分
        scorePool.value.takePoolScore();
        break
      case "03":    //向用户给分
        userScore.value.givePoints();
        break
      case "04":    //扣除用户积分
        userScore.value.deductScore();
        break
    }
  }
})


//用户积分操作
const userScore = ref({
  //给用户积分
  givePoints: () => {
    proxy.$request.post("/bus-room/givePoints", {
      roomId: room.value.roomId,
      receiverId: scoreActionModal.value.user.userId,
      score: scoreActionModal.value.number
    }).then(() => {
      scoreActionModal.value.close()
      scoreActionModal.value.loadingOff()
    }).catch(() => {
      scoreActionModal.value.close()
      scoreActionModal.value.loadingOff()
    })
  },
  //给用户积分
  deductScore: () => {
    proxy.$request.post("/bus-room/deductScore", {
      roomId: room.value.roomId,
      receiverId: scoreActionModal.value.user.userId,
      score: scoreActionModal.value.number
    }).then(() => {
      scoreActionModal.value.close()
      scoreActionModal.value.loadingOff()
    }).catch(() => {
      scoreActionModal.value.close()
      scoreActionModal.value.loadingOff()
    })
  }
})


//积分池相关方法
const scorePool = ref({
  /**
   * 向积分池给分
   */
  givePool: () => {
    proxy.$request.post(`/bus-room/givePoolScore/${room.value.roomId}/${scoreActionModal.value.number}`).then(() => {
      scoreActionModal.value.close()
      scoreActionModal.value.loadingOff()
    }).catch(() => {
      scoreActionModal.value.close()
      scoreActionModal.value.loadingOff()
    })
  },
  /**
   * 从积分池中取分
   */
  takePoolScore: () => {
    proxy.$request.post(`/bus-room/takePoolScore/${room.value.roomId}/${scoreActionModal.value.number}`).then(() => {
      scoreActionModal.value.close()
      scoreActionModal.value.loadingOff()
    }).catch(() => {
      scoreActionModal.value.close()
      scoreActionModal.value.loadingOff()
    });
  }
})


//积分流水弹框
const recordPopupRef = ref(null);


//定义确认弹框
const endGameModal = ref({
  title: '结束游戏',
  content: '游戏结束后，将不可以重新进入房间继续游戏，是否结束？',
  show: false,
  /**
   * 解散房间确认
   */
  verify: () => {
    endGameModal.value.show = true;
  },
  /**
   * 解散房间
   */
  endGame: () => {
    proxy.$request.post(`/bus-room/endGame/${room.value.roomId}`).then(() => {
      //解散后收到消息通知回到上一页
      endGameModal.value.show = false
    })
  }
})


</script>
<style lang="less" scoped>
.score-page {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  box-sizing: border-box;
  background-color: #f0f0f0;
  height: 100vh;

  .room-info {
    width: 100%;
    text-align: left;
    margin-bottom: 20px;
  }

  .room-id {
    font-size: 18px;
    font-weight: bold;
    color: #333;
  }

  .score-pool {
    width: 100%;
    text-align: center;
    margin-bottom: 20px;

    .pool-info {
      font-size: 20px;
      margin-bottom: 10px;
    }

    .pool-title {
      font-weight: bold;
      margin-right: 10px;
    }

    .pool-score {
      color: #1aad19;
    }

    .pool-actions {
      display: flex;
      justify-content: center;
      gap: 10px;
    }


    .pool-btn {
      background-color: #1aad19;
      color: #fff;
      padding: 8px 16px;
      border-radius: 20px;
      font-size: 14px;
    }

    .take-btn {
      background-color: #e6a33e;
      color: #fff;
      padding: 8px 16px;
      border-radius: 20px;
      font-size: 14px;
    }
  }

  .tax-info {
    font-size: 16px;
    color: #ff0000;
    margin-bottom: 10px;
  }

  .user-list {
    display: flex;
    flex-direction: column; /* 一列一个用户 */
    align-items: flex-start; /* 靠左对齐 */
    width: 100%;
    margin-bottom: 100px;
    overflow-y: auto;

    .user-card {
      display: flex;
      flex-direction: row; /* 水平排列头像和信息 */
      align-items: center; /* 垂直居中 */
      width: 100%;
      text-align: left; /* 文本左对齐 */
      margin-bottom: 20px;
      padding: 10px;
      box-sizing: border-box;
      border: 1px solid #ccc;
      border-radius: 8px;

      .avatar-container {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        overflow: hidden;
        margin-right: 15px; /* 头像和信息之间的间距 */
        border: 2px solid #ccc;
      }

      .avatar {
        width: 100%;
        height: 100%;
      }

      .user-info {
        display: flex;
        flex-direction: column; /* 姓名和得分竖着排列 */
        align-items: flex-start; /* 姓名和得分靠左 */
        justify-content: center; /* 上下居中 */
        width: 110px;
        white-space: nowrap; /* 禁止文本换行 */
        overflow: hidden; /* 隐藏超出部分 */
        text-overflow: ellipsis; /* 可选，超出部分用省略号表示 */

        .user-name {
          font-size: 16px;
          font-weight: bold;
        }

        .user-score {
          font-size: 20px;
          color: #888;
          display: flex;


          //正分数
          .user-score-number-plus{
            color: #388E3C;
          }

          //负分数
          .user-score-number-minus{
            color: #FF5722;
          }

        }

        .user-score-number-add {
          color: #388E3C;
          font-size: 20px;
        }

        .user-score-number-sub {
          color: #FF5722;
          font-size: 20px;
        }
      }

      .btns {
        display: flex;
        flex: 1;
        margin-left: 20px;
      }
    }
  }


  .end-btns {
    width: 100%;
    padding: 10px;
    box-sizing: border-box;
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */
    position: absolute;
    bottom: 30px;

    .view-record {
      flex: 1;
    }

    .end_game {
      margin-left: 20px;;
    }
  }
}
</style>


